package net.mikoo.seals.manage.web.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.mikoo.seals.biz.service.DevicesServices;
import net.mikoo.seals.biz.service.DevicesUsedServices;
import net.mikoo.seals.biz.service.SealServices;
import net.mikoo.seals.biz.service.WorkflowService;
import net.mikoo.seals.common.WebContext;
import net.mikoo.seals.common.enums.DevicesStatusEnum;
import net.mikoo.seals.common.exception.ParametersException;
import net.mikoo.seals.common.model.PageModel;
import net.mikoo.seals.manage.web.common.BaseController;
import net.mikoo.seals.model.Devices;
import net.mikoo.seals.model.DevicesAct;
import net.mikoo.seals.model.DevicesActQuery;
import net.mikoo.seals.model.DevicesQuery;
import net.mikoo.seals.model.DevicesUsed;
import net.mikoo.seals.model.DevicesUsedCert;
import net.mikoo.seals.model.DevicesUsedQuery;
import net.mikoo.seals.model.Seal;
import net.mikoo.seals.model.SealQuery;
import net.mikoo.seals.model.WorkflowSetting;
import net.mikoo.seals.utils.DateUtil;
import net.mikoo.seals.utils.IPUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/devices")
public class DevicesController extends BaseController {

	Logger logger = LoggerFactory.getLogger(DevicesController.class);

	@Autowired
	private DevicesServices devicesServices;
	
	@Autowired
	private SealServices sealServices;
	
	
	@Autowired
	private DevicesUsedServices devicesUsedServices;
	
	@Autowired
	private WorkflowService  workflowService;
	
	

	@RequestMapping("/list")
	public String list(DevicesQuery query, HttpServletRequest request, Model model) {
		
		Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		
		query.setExcludeStatus(DevicesStatusEnum.INIT.code());
		query.setCompanyId(companyId);
		PageModel<Devices> pm = devicesServices.getPageByQuery(query);
		model.addAttribute("pm", pm);
		model.addAttribute("query", query);
		
		return "devices/list";
	}
	
	
	
	@RequestMapping("/setting")
	public String setting(Long devicesId,HttpServletRequest request,Model model) {
		
		Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		
		Devices devices = devicesServices.getInfoById(devicesId);
		model.addAttribute("devices", devices);
		
		if(devices.getSealId() != null) {	
			SealQuery sealQuery = new SealQuery();
			sealQuery.setCompanyId(companyId);
			sealQuery.setSealId(devices.getSealId());
			Seal seal = sealServices.getInfoByQuery(sealQuery);
			model.addAttribute("seal", seal);
			
			//工作流设置
			List<WorkflowSetting> settings = workflowService.getSettingsByWorkflowId(seal.getWorkflowId());
			
			
			JSONArray array = new JSONArray();
			for (WorkflowSetting setting : settings) {
				JSONObject obj = new JSONObject();
				obj.put("name", setting.getPerson().getName());
				obj.put("portrait", setting.getPerson().getPortrait());
				obj.put("position", "");
				obj.put("id", setting.getPerson().getPartyId());
				array.add(obj);
			}
			model.addAttribute("settingsDatas", array.toString());
				
			if(seal.getSpecialWorkflowId() != null) {
				List<WorkflowSetting> specials = workflowService.getSettingsByWorkflowId(seal.getSpecialWorkflowId());
				model.addAttribute("specials", specials);
			}
			
			
		}
		
		
		return "devices/setting";
	}
	
	
	
	@RequestMapping("/setting/post")
	@ResponseBody
	public Map<String, Object> settingPost(Seal seal, HttpServletRequest request, Model model) {
		try {
			Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
			seal.setCompanyId(companyId);
			devicesServices.setting(seal);
			return result(SUCCESS, MSG_SUCCESS);
		} catch (ParametersException e) {
			logger.error("",e);
			return result(ERROR, e.getMessage());
		} catch (Exception e) {
			logger.error("",e);
			return result(ERROR, MSG_SYSTEM_ERROR);
		}
	}
	
	
	
	
	
	//=============
	
	@RequestMapping("/form")
	public String form(DevicesQuery query,HttpServletRequest request,Model model) {
		
		Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		
		
		SealQuery sealQuery = new SealQuery();
		sealQuery.setCompanyId(companyId);
		sealQuery.setSealId(query.getSealId());
		Seal seal = sealServices.getInfoByQuery(sealQuery);
		
		model.addAttribute("seal", seal);
		
		return "devices/form";
	}
	
	
	@RequestMapping("/info")
	public String info(DevicesQuery query,HttpServletRequest request,Model model) {
		
		Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		query.setCompanyId(companyId);
		Devices devices = devicesServices.getInfoByQuery(query);
		
		model.addAttribute("devices", devices);
		return "devices/info";
	}
	
	
	@RequestMapping("/usedlist")
	public String usedlist(DevicesUsedQuery query,HttpServletRequest request,Model model) {
		
		Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		DevicesQuery devicesQuery = new DevicesQuery();
		devicesQuery.setCompanyId(companyId);
		devicesQuery.setDevicesId(query.getDevicesId());
		Devices devices = devicesServices.getInfoByQuery(devicesQuery);
		
		query.setCompanyId(companyId);
		query.setOrderType("DESC");
		query.setOrderColumn("USED_TIME");
		PageModel<DevicesUsed> pm = devicesUsedServices.getPageByQuery(query);
		
		model.addAttribute("devices", devices);
		model.addAttribute("pm", pm);
		return "devices/usedlist";
	}
	
	
	
	
	
	
	/**
	 * 模拟测试添加
	 * @param devices
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Map<String,Object> add(Devices devices,HttpServletRequest request,Model model) {
		
		try {
			
			Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
			devices.setCompanyId(companyId);
			//devicesServices.bind(devices, getCurrentUserLoginId(request, WebContext.ADMIN_LOGIN_SESSION_KEY));
			
			
			
			devices.setDevicesCode(UUID.randomUUID().toString());
			//devices.setDevicesVerson(1);
			devices.setProduceDate(new Date());
			devices.setModel("v1.0");
			//devices.setDevicesStatus(DevicesStatusEnum.WAIT_INSTALL.code());
			//devices.setBindingTime(new Date());
			devices.setExpireDate(DateUtil.addMonth(new Date(), 6));
			//devices.setCreateTime(new Date());
			
			
			devicesServices.save(devices);
			
			return result(SUCCESS, "添加成功");
		}catch (ParametersException e) {
			logger.error("",e);
			return result(ERROR, e.getMessage());
		}catch (Exception e) {
			logger.error("",e);
			return result(ERROR, MSG_SYSTEM_ERROR);
		}
	}
	
	
	@RequestMapping("/install")
	public String install(Devices devices,HttpServletRequest request,Model model) {
		//判断是否已经
		
		return "devices/install";
	}
	
	/**
	 * 确认完成安装
	 * @param devices
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/install/confirm")
	@ResponseBody
	public Map<String,Object> installConfirm(Devices devices,HttpServletRequest request,Model model) {
		
		try{
			
			Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
			devices.setCompanyId(companyId);
			devicesServices.installConfirm(devices, getCurrentUserLoginId(request, WebContext.ADMIN_LOGIN_SESSION_KEY));
			
			return result(SUCCESS, "操作成功");
		}catch (ParametersException e) {
			logger.error("",e);
			return result(ERROR, e.getMessage());
		}catch (Exception e) {
			logger.error("",e);
			return result(ERROR, MSG_SYSTEM_ERROR);
		}
		
	}
	
	
	@RequestMapping("/used")
	@ResponseBody
	public Map<String,Object> used(DevicesUsed devicesUsed,HttpServletRequest request,Model model) {
		
		try{
			Long partyId = getCurrentPartyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
			Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
			devicesUsed.setCompanyId(companyId);
			devicesUsed.setPartyId(partyId);
			
			devicesUsed.setUsedIp(IPUtil.getRemoteAddr(request));
			
			devicesServices.used(devicesUsed);
			
			return result(SUCCESS, "操作成功");
		}catch (ParametersException e) {
			logger.error("",e);
			return result(ERROR, e.getMessage());
		}catch (Exception e) {
			logger.error("",e);
			return result(ERROR, MSG_SYSTEM_ERROR);
		}
		
	}
	/**
	 * 上传凭证
	 * @param devicesUsed
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/upcert")
	@ResponseBody
	public Map<String,Object> upcert(DevicesUsedCert cert,HttpServletRequest request,Model model) {
		
		try{
			//Long partyId = getCurrentPartyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
			Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
			cert.setCompanyId(companyId);
			
			
			devicesServices.upcert(cert);
			
			return result(SUCCESS, "操作成功");
		}catch (ParametersException e) {
			logger.error("",e);
			return result(ERROR, e.getMessage());
		}catch (Exception e) {
			logger.error("",e);
			return result(ERROR, MSG_SYSTEM_ERROR);
		}
		
	}
	
	
	@RequestMapping("/publish")
	@ResponseBody
	public Map<String,Object> publish(Devices devices,HttpServletRequest request) {
		try {
			
			Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
			devices.setCompanyId(companyId);
			devicesServices.publish(devices, getCurrentUserLoginId(request, WebContext.ADMIN_LOGIN_SESSION_KEY));
			
			return result(SUCCESS, MSG_SUCCESS);
		}catch (ParametersException e) {
			logger.error("",e);
			return result(ERROR, e.getMessage());
		}catch (Exception e) {
			logger.error("",e);
			return result(ERROR, MSG_SYSTEM_ERROR);
		}
	}
	
	@RequestMapping("/test")
	public String test(Devices devices,HttpServletRequest request,Model model) {
		
		
		Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		Long partyId = getCurrentPartyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		
		DevicesActQuery query = new DevicesActQuery();
		query.setCompanyId(companyId);
		query.setDevicesId(devices.getDevicesId());
		query.setPartyId(partyId);
		
		List<DevicesAct> acts = devicesServices.getValidActListByQuery(query);
//		//判断是否有使用记录 有跳转到使用二维码 没有则跳转到申请页面，
//		if(acts == null || acts.isEmpty()) {
//			return redirect("/apply/test.htm?devicesId="+devices.getDevicesId());
//		}
		
		model.addAttribute("acts", acts);
		model.addAttribute("devices", devices);
		return "devices/test";
	}
	
//	@RequestMapping("/setting")
//	public String setting(Long devicesId,HttpServletRequest request,Model model) {
//		
//		Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
//		
//		Devices devices = devicesServices.getInfoById(devicesId);
//		model.addAttribute("devices", devices);
//		
//		WorkflowQuery query = new WorkflowQuery();
//		query.setCompanyId(companyId);
//		query.setIsEnable("Y");
//		List<Workflow> workflows = workflowService.getListByQuery(query);
//		model.addAttribute("workflows", workflows);
//		return "devices/setting";
//	}
//	
//	
//	@RequestMapping("/setting/post")
//	@ResponseBody
//	public Map<String, Object> settingPost(Devices devices, HttpServletRequest request, Model model) {
//		try {
//			Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
//			devices.setCompanyId(companyId);
//			devicesServices.setting(devices);
//			return result(SUCCESS, MSG_SUCCESS);
//		} catch (ParametersException e) {
//			logger.error("",e);
//			return result(ERROR, e.getMessage());
//		} catch (Exception e) {
//			logger.error("",e);
//			return result(SUCCESS, MSG_SYSTEM_ERROR);
//		}
//	}

}
